package demo.module.file.controller;

import demo.module.file.daomain.FileInfo;
import demo.util.FileUpLoadUtil;
import demo.util.NetworkUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import java.util.Date;

/**
 * Created by haol on 2017/6/27.
 */
@Controller
@RequestMapping("/file")
public class FileController {
        private Logger logger = LoggerFactory.getLogger(FileController.class);

        @RequestMapping("/submit")
        public String skip() {
                return "submit";
        }

        @RequestMapping("/upload")
        public String uploadFile(MultipartFile file,
                                 Model model, FileInfo fileInfo, HttpServletRequest request) {
                fileInfo.setUpIp(NetworkUtil.getIpAddress(request));
                String fileName = file.getOriginalFilename();
                logger.info("fileName:" + fileName);
                try {
                        //拿到输出流，同时重命名上传的文件
                        FileUpLoadUtil.up(file, "D:\\");
                        String success = "文件" + file.getOriginalFilename() + "上传成功";
                        model.addAttribute("tips", success);
                } catch (Exception e) {
                        e.printStackTrace();
                        String error = "文件" + file.getOriginalFilename() + "上传失败,";
                        model.addAttribute("tips", error);
                        model.addAttribute("error", e.getMessage());
                        logger.error(e.getMessage());
                        logger.error("上传出错");
                } finally {
                        model.addAttribute("name", fileName);
                        model.addAttribute("date", new Date());
                }
                return "feed";
        }
}
